package com.xiake.zojcodesandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.xiake.zojcodesandbox.model.ExecuteCodeRequest;
import com.xiake.zojcodesandbox.model.ExecuteCodeResponse;
import com.xiake.zojcodesandbox.model.ExecuteMessage;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemplate{
    private static final long Max_Execute_Time = 5000;
    private static final Boolean FIRST_INIT = true;


    //重写代码沙箱方法实现运行代码的方式
    @Override
    public List<ExecuteMessage> runCode(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        //执行文件
        //1.拉取目标镜像
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String image="openjdk:8-alpine";
        if(FIRST_INIT){
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像状态:" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion(); // 等待下载完成，不然一直阻塞
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常！");
                throw new RuntimeException(e);
            }

            System.out.println("下载完成");
        }

        //2.创建一个可交互的容器,类比于容器池，一直有一个可运行的容器，而且有文件
        //在创建容器时，就将要编译的文件复制到文件
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        //将本地用户代码复制到容器内执行
        hostConfig.setBinds(new Bind(userCodeParentPath,new Volume("/app")));
        hostConfig.withMemory(100 * 1000 * 1000L);    //限制容器的内存大小
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withSecurityOpts(Arrays.asList("安全管理器的配置")); //限制用户的权限
        //seccomp的安全管理器的json
        CreateContainerResponse containerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)    //限制访问网络资源
                .withAttachStderr(true)   //获取本地的终端命令输入
                .withAttachStdin(true)
                .withAttachStdout(true)   //获取本地终端的输出
                .withTty(true)            //启用交互式容器
                .exec();
        String containerId = containerResponse.getId();

        //3.启动容器,把手动执行容器命令改为程序执行
        //docker start 6198822da9a0
        dockerClient.startContainerCmd(containerId).exec();

        //执行命令
        //docker exec 6198822da9a0 java -cp /app Main 1 2
        ExecCreateCmd execCreateCmd = dockerClient.execCreateCmd(containerId);
        ArrayList<ExecuteMessage> executeMessageList= new ArrayList<>();
        for (String input : inputList) {
            StopWatch stopWatch = new StopWatch();
            //未输入参数的字符串
            String[] baseCmd=new String[]{"java","-cp","/app","Main"};
            //输入用例列表中的参数。如“1 2”,需要将数组中的每一个字符串进行拆分
            String[] param = input.split(" ");
            //最终组合成的命令
            String[] fullCmd = ArrayUtil.append(baseCmd, param);
            //创建要执行的命令
            ExecCreateCmdResponse execCreateCmdResponse = execCreateCmd
                    .withCmd(fullCmd)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令"+execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            String execId = execCreateCmdResponse.getId();
            final boolean[] timeout={true};
            //执行刚才创建的命令
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback(){
                @Override
                public void onComplete() { //在执行命令的回调函数去控制，即代码执行完判断是否超时
                    timeout[0]=false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };

            //监控内存占用状态
            //获得此段程序在docker容器中的执行状态
//            long maxMemory=0;
            final long[] maxMemory = {0L};
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    Long memoryUsage = statistics.getMemoryStats().getUsage();
                    maxMemory[0]=Math.max(maxMemory[0],memoryUsage);
                    System.out.println(memoryUsage);


                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });

            try {
                stopWatch.start();
                dockerClient
                        .execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(Max_Execute_Time, TimeUnit.MILLISECONDS); //超时就停止执行
                stopWatch.stop();
            } catch (InterruptedException e) {
                System.out.println("执行命令失败！");
                executeMessage.setExitValue(4);
                throw new RuntimeException(e);
            }


            //封装执行信息
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setMessage(message[0]);
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        return executeMessageList;
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        return super.executeCode(executeCodeRequest);
    }
}
